<template>
  <div class="lr-top">
    <div v-if="appConfig.theme.nav == 'mix'" class="top-bar__left">
      <top-logo :isShowProject="!isNotMeuns" ref="topLogo"></top-logo>
      <div v-show="false" class="top-bar__item">
        <top-menu ref="topMenu"></top-menu>
      </div>
    </div>
    <div class="top-bar__right">
      <el-tooltip 
                  effect="dark"
                  :content="isFullScren?$t('退出全屏'):$t('全屏')"
                  placement="bottom">
        <div class="top-bar__item">
          <i :class="isFullScren?'el-icon-full-screen':'el-icon-full-screen'"
             @click="handleScreen"></i>
        </div>
      </el-tooltip>
      <el-tooltip 
        v-if="isOpenIM"
                  effect="dark"
                  :content="$t('联系')"
                  placement="bottom">
        <div class="top-bar__item" @click="handleOpenChat">
          <i class="el-icon-chat-dot-square"></i>
          <el-badge v-if="chatNum" :value="chatNum" :max="99" style="margin-left: -8px;margin-top: -8px;"></el-badge>
        </div>
      </el-tooltip>

      <el-tooltip 
        v-if="isOpenIM"
                  effect="dark"
                  :content="$t('消息')"
                  placement="bottom">
        <div class="top-bar__item" style="margin-right:16px;" @click="handleOpenMessge">
          <i class="el-icon-bell"></i>
          <el-badge v-if="messageNum" :value="messageNum" :max="99" style="margin-left: -8px;margin-top: -8px;"></el-badge>
        </div>
      </el-tooltip>


      <el-dropdown>
        <div class="el-dropdown-link">
          <el-avatar :size="24" :src="avatar">
            <img :src="`${rootUrl}img/admin/head.png`"/>
          </el-avatar>
          {{loginInfo.f_RealName}}
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-if="!isNotUserInfo">
            <router-link to="/organization/loginuser/index">{{$t('个人信息')}}</router-link>
          </el-dropdown-item>
          <el-dropdown-item @click.native="handleRemoveCache" >
            {{$t('清空缓存')}}
          </el-dropdown-item>
          <el-dropdown-item @click.native="handleFramework" >
            {{$t('关于框架')}}
          </el-dropdown-item>
          <el-dropdown-item @click.native="logout"
                            divided>{{$t('退出登录')}}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <l-dialog
      :title="$t('关于框架')"
      :visible.sync="frameworkVisible"
      :hasBtns="false"
      :height="240"
      width="560px"
      >
      <div class="l-rblock" >
        <img class="l-framework-img" :src="`${rootUrl}img/admin/logo2.svg`" >
        <div class="l-framework-text" >
          <div class="l-framework-title" >
            <a :href="appConfig.url" target="_blank"> {{appConfig.title}}</a>
          </div>
          <div>{{$t("版本")}}：{{appConfig.version}}-{{appConfig.subVersion}}</div>
        </div>
        <div class="l-framework-footer">
          <a :href="appConfig.url" target="_blank">{{appConfig.company}}</a>
        </div>
      </div>
    </l-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex"
import { fullscreenToggel, listenfullscreen } from "../../../util/util"
import topMenu from "./top-menu"
import topLogo from "./top-logo"

export default {
  components: {
    topMenu,
    topLogo
  },
  name: "top",
  props:{
    isNotMeuns:{
      type:Boolean,
      default:false
    },
    isNotUserInfo:{
      type:Boolean,
      default:false
    }
  },
  provide () {
    return {
      top: this
    };
  },
  data () {
    return {
      frameworkVisible:false,
      frameworkSettingVisible:false,

      isOpenIM:false,
      connection:null,

      chatNum:0,
      chatVisible:false,

      messageNum:0,
      messageVisible:false,

    };
  },
  filters: {},
  created () { },
  mounted () {
    listenfullscreen(this.setScreen);
    this.initIM()
  },
  computed: {
    ...mapGetters([
      "isFullScren",
      "modulesGroup",
    ]),
    avatar:function(){
      return this.loginInfo.f_HeadIcon ? `${this.apiUrl}organization/user/img/${this.loginInfo.f_HeadIcon}?token=${this.token}` : `${this.rootUrl}img/admin/head.png`
    },
  },
  methods: {
    handleScreen () {
      fullscreenToggel();
    },
    setScreen () {
      this.$store.commit("app/SET_FULLSCREN");
    },
    logout () {
      this.$confirm(this.$t("您确定要退出当前系统吗?"), this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning"
      }).then(() => {
        this.$store.dispatch("organization/user/fedLogOut").then(() => {
          this.$router.push({ path: "/login" })
        })
      }).catch(() => {
          this.$message({
              type: 'info',
              message: '已取消退出'
          });          
      })
    },
    handleRemoveCache(){
      this.$confirm(this.$t("您确定要清空缓存吗?"), this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning"
      }).then(async () => {
        const api = window.$api.organization.user
        await api.removeCache()
        location.reload()
      }).catch(() => {
          this.$message({
              type: 'info',
              message: '已取消退出'
          });          
      })
    },
    handleFramework(){
      this.frameworkVisible = true;
    },
    initTopMenu(){
      if(this.appConfig.theme.nav == 'side'){
        this.$store.commit('system/module/setMenu', this.modulesGroup['0'] || []);
      }
      else{
        this.$refs.topMenu && this.$refs.topMenu.initTopMenu();
      }
    }, 
    openFrameworkSetting(){
      this.frameworkSettingVisible = true;
    },
    handleNavClick(type){
      this.$store.commit("app/SET_THEME_NAV", type)
      this.$nextTick(() => {
        this.initTopMenu()
      })
    },


    // 即时通讯服务
    async initIM(){
      if(!this.appConfig.imOpen){
        return
      }
      const api = window.$api.message.contact
      const data = (await this.$awaitWraper(api.getList())) || []
      let num = 0
      data.forEach(item => {
        num += item.f_NoReadNum
      })
      this.chatNum = num

      // 刷新数据
      const apiMsg = window.$api.message.msg
      this.messageNum = await this.$awaitWraper(apiMsg.getSysNum())


      this.connection = new window.signalR.HubConnectionBuilder().withUrl(`${this.imUrl}/ChatsHub`).build()
      this.connection.on('revMsg', (userId, msg, dateTime,id, isSystem) => {


        if(isSystem == 1){
          // 系统消息
          //this.messageNum += 1
          
          if(this.messageVisible && this.$refs.messageList){
            this.$refs.messageList.refresh()
          }
          else{
            this.refreshNum()
          }
        }
        else if(isSystem == 100){
          // 刷新
          this.refreshNum()
        }
        else{
          const item = {
            f_MsgId:id,
            f_SendUserId:userId,
            f_RecvUserId:this.loginInfo.f_UserId,
            f_Content:msg,
            f_CreateDate:dateTime,
            f_IsSystem:isSystem
          }
          if(this.chatVisible && this.$refs.chatList){
            if(this.$refs.chatList.isAddNum(item)){
              this.chatNum += 1
            }
          }
          else{
            this.chatNum += 1
          }
          this.$store.commit('message/msg/add',item)
        }
      })

      this.connection.onclose(function(e){
        console.log('Connection closed!', e)
      })

      this.connection.start().then(() => {
        this.isOpenIM = true
        this.connection.invoke("SendInfo", this.loginInfo.f_UserId)
      }).catch(function (err) {
        console.error(err.toString())
      })
    },

    // 内部聊天
    handleOpenChat(){
      this.chatVisible = true
    },
    handleChatOpened(){
      this.$refs.chatList && this.$refs.chatList.loadData()
    },
    sendChat(userId,msg,id){
      if(this.connection.state == 1){
        this.connection.invoke("SendMsg", this.loginInfo.f_UserId,userId, msg,id, 0)
      }
    },
    updateChatNum(num){
      this.chatNum -= num
      if(this.chatNum < 0){
        this.chatNum = 0
      }
    }
  }
};
</script>

<style lang="scss" scoped>
  .l-framework-img{
    position: absolute;
    top:64px;
    right: 50%;
    margin-right: 40px;
    height: 64px;
  }
  .l-framework-text{
    position: absolute;
    top:73px;
    left: 50%;
    margin-left: -24px;
    width: 284px;
  }
  .l-framework-title{
    font-size: 18px;
  }
  .l-framework-footer{
    position: absolute;
    bottom: 16px;
    width: 100%;
    text-align: center;
  }
  
</style>